'use client';

import { useEffect, useState, useCallback } from 'react';
import { motion } from 'framer-motion';
import { useRouter } from 'next/navigation';
import {
  BookOpen,
  Star,
  Clock,
  Users,
  ChevronRight,
  Filter,
  Search,
  ArrowLeft
} from 'lucide-react';
import { ALL_CATEGORIES, TOPICS_BY_CATEGORY, TOPICS_BY_GRADE, DIFFICULTY_LABELS } from '@/data/topics-index';

interface Topic {
  id: string;
  name: string;
  description: string;
  category: string;
  gradeLevel: number[];
  difficulty: number;
  examples: string[];
  keyPoints: string[];
  prerequisites?: string[];
}

export default function LearnPage() {
  const [topics, setTopics] = useState<Topic[]>([]);
  const [filteredTopics, setFilteredTopics] = useState<Topic[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [selectedGrade, setSelectedGrade] = useState<number>(0);
  const [selectedDifficulty, setSelectedDifficulty] = useState<number>(0);
  const [searchQuery, setSearchQuery] = useState('');
  const [userGrade, setUserGrade] = useState<number>(5);
  const [loading, setLoading] = useState(true);

  const router = useRouter();

  const loadUserProfile = useCallback(async () => {
    try {
      // 从API获取用户信息
      const response = await fetch('/api/auth/me', {
        credentials: 'include'
      });

      if (response.ok) {
        const result = await response.json();
        if (result.success && result.data && result.data.profile) {
          const grade = result.data.profile.grade || 5;
          setUserGrade(grade);
          setSelectedGrade(grade); // 默认显示用户年级的内容
        }
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
    }
  }, []);

  const loadTopics = useCallback(async () => {
    try {
      // 直接使用本地知识点数据
      const localTopics = Object.values(TOPICS_BY_CATEGORY).flat();
      setTopics(localTopics as Topic[]);
    } catch (error) {
      console.error('加载知识点失败:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  const filterTopics = useCallback(() => {
    let filtered = [...topics];

    // 按分类筛选
    if (selectedCategory !== 'all') {
      filtered = filtered.filter(topic => topic.category === selectedCategory);
    }

    // 按年级筛选
    if (selectedGrade > 0) {
      filtered = filtered.filter(topic =>
        topic.gradeLevel.includes(selectedGrade)
      );
    }

    // 按难度筛选
    if (selectedDifficulty > 0) {
      filtered = filtered.filter(topic => topic.difficulty === selectedDifficulty);
    }

    // 按搜索关键词筛选
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(topic =>
        topic.name.toLowerCase().includes(query) ||
        topic.description.toLowerCase().includes(query) ||
        topic.keyPoints.some(point => point.toLowerCase().includes(query))
      );
    }

    setFilteredTopics(filtered);
  }, [topics, selectedCategory, selectedGrade, selectedDifficulty, searchQuery]);


  // 将副作用放在依赖定义之后，避免“先使用后声明”的类型错误
  useEffect(() => {
    loadTopics();
    loadUserProfile();
  }, [loadTopics, loadUserProfile]);

  useEffect(() => {
    filterTopics();
  }, [filterTopics]);

  function getDifficultyColor(difficulty: number) {
    const colors = {
      1: 'text-green-600 bg-green-100',
      2: 'text-blue-600 bg-blue-100',
      3: 'text-yellow-600 bg-yellow-100',
      4: 'text-orange-600 bg-orange-100',
      5: 'text-red-600 bg-red-100'
    };
    return colors[difficulty as keyof typeof colors] || 'text-gray-600 bg-gray-100';
  }

  function getCategoryIcon(category: string) {
    const icons = {
      '基础计算': '🧮',
      '行程问题': '🚗',
      '几何图形': '📐',
      '数论基础': '🔢',
      '逻辑推理': '🧠',
      '应用问题': '📊',
      '组合计数': '🎲',
      '高级思维': '🎯',
      '代数基础': '📈',
      '函数': '📉',
      '几何基础': '📏',
      '数论进阶': '🔣',
      '组合数学': '🎪',
      '概率统计': '📋'
    };
    return icons[category as keyof typeof icons] || '📚';
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <div className="glassmorphism p-8 rounded-2xl">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">加载知识点中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
      {/* 导航栏 */}
      <nav className="glassmorphism-nav sticky top-0 z-50 backdrop-blur-md bg-white/10 border-b border-white/20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center space-x-4">
              <button
                onClick={() => router.push('/dashboard')}
                className="p-2 rounded-lg hover:bg-white/20 transition-colors"
                title="返回学习仪表盘"
              >
                <ArrowLeft className="w-5 h-5 text-gray-600" />
              </button>
              <h1 className="text-2xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">
                知识点学习
              </h1>
            </div>
          </div>
        </div>
      </nav>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 筛选区域 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-white/80 backdrop-blur-sm p-6 rounded-2xl shadow-lg border border-gray-200/50 mb-8"
        >
          <div className="flex flex-col lg:flex-row gap-4">
            {/* 搜索框 */}
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                <input
                  type="text"
                  placeholder="搜索知识点..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 bg-white/50 border border-white/20 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                />
              </div>
            </div>

            {/* 筛选器 */}
            <div className="flex flex-wrap gap-4">
              <select
                value={selectedCategory}
                onChange={(e) => setSelectedCategory(e.target.value)}
                className="px-4 py-2 bg-white/50 border border-white/20 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
              >
                <option value="all">所有分类</option>
                {ALL_CATEGORIES.map(category => (
                  <option key={category} value={category}>
                    {getCategoryIcon(category)} {category}
                  </option>
                ))}
              </select>

              <select
                value={selectedGrade}
                onChange={(e) => setSelectedGrade(Number(e.target.value))}
                className="px-4 py-2 bg-white/50 border border-white/20 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
              >
                <option value={0}>所有年级</option>
                {[1,2,3,4,5,6,7,8,9].map(grade => (
                  <option key={grade} value={grade}>
                    {grade}年级
                  </option>
                ))}
              </select>

              <select
                value={selectedDifficulty}
                onChange={(e) => setSelectedDifficulty(Number(e.target.value))}
                className="px-4 py-2 bg-white/50 border border-white/20 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
              >
                <option value={0}>所有难度</option>
                {Object.entries(DIFFICULTY_LABELS).map(([level, label]) => (
                  <option key={level} value={Number(level)}>
                    {label}
                  </option>
                ))}
              </select>
            </div>
          </div>

          <div className="mt-4 text-sm text-gray-600">
            找到 {filteredTopics.length} 个知识点
            {userGrade > 0 && selectedGrade === userGrade && (
              <span className="ml-2 px-2 py-1 bg-indigo-100 text-indigo-700 rounded-full text-xs">
                推荐给{userGrade}年级
              </span>
            )}
          </div>
        </motion.div>

        {/* 知识点列表 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredTopics.map((topic, index) => (
            <motion.div
              key={topic.id}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: index * 0.1 }}
              className="bg-white/80 backdrop-blur-sm p-6 rounded-2xl shadow-lg border border-gray-200/50 hover:scale-105 hover:shadow-xl transition-all cursor-pointer"
              onClick={() => router.push(`/learn/${topic.id}`)}
            >
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center space-x-2">
                  <span className="text-2xl">{getCategoryIcon(topic.category)}</span>
                  <div>
                    <h3 className="font-semibold text-gray-800">{topic.name}</h3>
                    <p className="text-sm text-gray-600">{topic.category}</p>
                  </div>
                </div>
                <ChevronRight className="w-5 h-5 text-gray-400" />
              </div>

              <p className="text-sm text-gray-600 mb-4 line-clamp-2">
                {topic.description}
              </p>

              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <span className={`px-2 py-1 rounded-full text-xs font-medium ${getDifficultyColor(topic.difficulty)}`}>
                    {DIFFICULTY_LABELS[topic.difficulty as keyof typeof DIFFICULTY_LABELS]}
                  </span>
                  <span className="text-xs text-gray-500">
                    {topic.gradeLevel.join('-')}年级
                  </span>
                </div>
                <div className="flex items-center space-x-1 text-xs text-gray-500">
                  <BookOpen className="w-4 h-4" />
                  <span>{topic.keyPoints.length}个要点</span>
                </div>
              </div>
            </motion.div>
          ))}
        </div>

        {filteredTopics.length === 0 && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="text-center py-12"
          >
            <BookOpen className="w-16 h-16 text-gray-400 mx-auto mb-4" />
            <h3 className="text-xl font-semibold text-gray-600 mb-2">没有找到匹配的知识点</h3>
            <p className="text-gray-500">尝试调整筛选条件或搜索关键词</p>
          </motion.div>
        )}
      </div>
    </div>
  );
}
